package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.exception.BizException;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.PurchaseService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MerageVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
@Slf4j
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                Wrappers.<PurchaseEntity>lambdaQuery()
                        .in(PurchaseEntity::getStatus,
                                WareConstant.PurchaseStatusEnum.CREATED.getCode(),
                                WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MerageVo merageVo) {
        Long purchaseId = merageVo.getPurchaseId();
        if (purchaseId == null) {
            // 没有选择采购单, 需要新建一个采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());

            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        // 确认采购单状态是 0,1 才可以合并
        PurchaseEntity purchase = this.getById(purchaseId);
        if (WareConstant.PurchaseStatusEnum.CREATED.getCode() != purchase.getStatus()
                && WareConstant.PurchaseStatusEnum.ASSIGNED.getCode() != purchase.getStatus()) {
            throw new BizException("采购需要时新建或者已分配的");
        }

        List<Long> purchaseDetailIds = merageVo.getItems();
        Long finalPurchaseId = purchaseId;
        // 更新采购需求状态为已分配
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailIds.stream().map(purchaseDetailId -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(purchaseDetailId);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        // 更新采购单时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void received(List<Long> ids) {
        // 1. 确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> purchaseEntities = this.listByIds(ids);
        List<PurchaseEntity> purchaseEntityList = purchaseEntities.stream()
                // 过滤选择采购单状态为新建或者已分配的
                .filter(purchaseEntity -> {
                    if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                            purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                        // 设置状态为已领取
                        purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
                        purchaseEntity.setUpdateTime(new Date());
                        return true;
                    }
                    return false;
                }).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(purchaseEntityList)) {
            log.info("没有能被领取的采购单 purchaseEntityList: {}", purchaseEntityList);
            return;
        }

        // 2. 改变采购单状态
        this.updateBatchById(purchaseEntityList);

        // 3. 改变采购项目状态
        // 采购单id集合
        List<Long> purchaseIds = purchaseEntityList.stream().map(PurchaseEntity::getId).collect(Collectors.toList());
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.list(
                Wrappers.<PurchaseDetailEntity>lambdaQuery()
                        .in(PurchaseDetailEntity::getPurchaseId, purchaseIds)
        );
        List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailEntities.stream().map(purchaseDetailEntity -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(purchaseDetailEntity.getId());
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void finish(PurchaseDoneVo purchaseDoneVo) {
        // 2. 改变采购项状态
        // 采购项是否全部完成
        boolean isAllFinished = true;
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> detailUpdates = new ArrayList<>();
        for(PurchaseItemDoneVo purchaseItemDoneVo : items) {
            if (WareConstant.PurchaseDetailStatusEnum.PURCHASE_FAILED.getCode() == purchaseItemDoneVo.getStatus()) {
                isAllFinished = false;
            }
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(purchaseItemDoneVo.getItemId());
            purchaseDetailEntity.setStatus(purchaseItemDoneVo.getStatus());

            detailUpdates.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(detailUpdates);


        // 1. 改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        if (isAllFinished) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISHED.getCode());
        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode());
        }
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

        // 3. 将采购成功 进行入库
        // 采购完成的采购项id
        List<Long> finishedPurchaseIds = detailUpdates.stream()
                .filter(purchaseDetailEntity -> WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode() == purchaseDetailEntity.getStatus())
                .map(PurchaseDetailEntity::getId)
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(finishedPurchaseIds)) {
            log.info("采购项全未完成, finishedPurchaseIds: {}", finishedPurchaseIds);
            return;
        }

        List<PurchaseDetailEntity> finishedPurchases = purchaseDetailService.listByIds(finishedPurchaseIds);
        List<WareSkuEntity> wareSkuEntities = finishedPurchases.stream()
                .map(purchaseDetailEntity -> {
                    WareSkuEntity wareSkuEntity = new WareSkuEntity();
                    wareSkuEntity.setSkuId(purchaseDetailEntity.getSkuId());
                    wareSkuEntity.setWareId(purchaseDetailEntity.getWareId());
                    wareSkuEntity.setStock(purchaseDetailEntity.getSkuNum());
                    return wareSkuEntity;
                }).collect(Collectors.toList());

        // 保存商品库存
        wareSkuService.addStock(wareSkuEntities);

    }

}
